//
//  Nine_nineViewController.m
//  EarnBao
//
//  Created by xiaohui on 15/2/5.
//  Copyright (c) 2015年 杭州赚宝科技有限公司. All rights reserved.
//

#import "Nine_nineViewController.h"
#import "Nine_nineCollectionViewCell.h"
#import "DetailViewController.h"
#import "Nine_nine.h"
#import "EarnBao-API.h"
#import "Reachability.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "DownLoadData.h"
#import "UpLoadData.h"

@interface Nine_nineViewController ()<DownLoadDataDelegate>  //遵守协议
{
    int pageNumber;  //页码
}
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) Reachability *whole_conn;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic ,retain) NSMutableArray *waterfallArray;

@end

@implementation Nine_nineViewController

//销毁通知
- (void)dealloc
{
    [self.whole_conn stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//构建子视图
-(void)setSubviews
{
    //瀑布流主体
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width*11/24, self.view.bounds.size.width*11/18);
    flowLayout.sectionInset = UIEdgeInsetsMake(self.view.bounds.size.width/48, self.view.bounds.size.width/48, self.view.bounds.size.width/48, self.view.bounds.size.width/48);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;  //设置代理
    _collectionView.dataSource = self;  //设置数据源
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    [self.view addSubview:_collectionView];
}

//数据加载完成之前显示的菊花圈
- (void)setProgressHud
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [_hud show:YES];
}

//视图加载完成
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=WHITE_COLOR;
    self.navigationItem.title = @"九块九";

    //构建子视图
    [self setSubviews];
    
    
    //初始化对象数组
    self.waterfallArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    //页码初始值设置为2
    pageNumber = 2;
    
    //视图加载完成就请求数据为了做缓存
    [self loadData];
    
    //上传版本号
    [self upVersion];
    
    //注册一个通知用来实时监测网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    //创建一个全局的网络对象
    self.whole_conn = [Reachability reachabilityForInternetConnection];
    //开启通知
    [self.whole_conn startNotifier];
    
    
    //监测网络状态的变化
    [self networkStateChange];
}

#pragma mark ---实时监测网络状态的改变(一切数据请求和数据显示的相关处理均以网络状态的不同为基准进行！)---

//监测网络状态的变化
- (void)networkStateChange
{
    [self checkNetworkState];
}

//检查网络状态
- (void)checkNetworkState
{
    //1.创建wifi网络对象
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    //2.创建手机网络对象(2G/3G/4G，也就是平时常说的手机流量)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    //3.判断当前app的网络连接状态，通常分为以下三种情况：
    
    //有wifi连接(包括两种情况：1.只有wifi  2.手机网络和wifi同时存在，此时wifi会自动替换掉手机网络)
    if ([wifi currentReachabilityStatus] != NotReachable) {
        
        [self setProgressHud];
        [self addHeader];
        [self addFooter];
        [_hud hide:YES];
    }
    
    //只有手机网络
    if ([conn currentReachabilityStatus] != NotReachable && [wifi currentReachabilityStatus] == NotReachable) {
        
        [self setProgressHud];
        [self addHeader];
        [self addFooter];
        [_hud hide:YES];
    }
}

#pragma mark ---将当前使用的app的版本号上传给服务器端---

- (void)upVersion
{
    UpLoadData *handle = [UpLoadData shareDataHandle];
    [handle upLoadDataWithURL:kHomePage_ProductList];
}

#pragma mark ---从服务器请求数据，用代理刷新数据---

//加载数据
- (void)loadData
{
    //初始化请求对象
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //GET请求(也可以用POST请求)
    [manager GET:kNine_nineProductList parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         __block Nine_nineViewController *nine_nineVC = self;
         
         NSDictionary *sourceDic = responseObject[@"products"];
         
         for (NSDictionary *dic in sourceDic) {
             
             Nine_nine *nine_nine = [[Nine_nine alloc] init];
             [nine_nine setValuesForKeysWithDictionary:dic];
             [self.waterfallArray addObject:nine_nine];
             
         }
         [nine_nineVC.collectionView reloadData];
     }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"服务器出错了！相关错误信息是:%@",error);
         }];
    
//    DownLoadData *handle = [DownLoadData shareDataHandle];
//    //设置代理
//    handle.delegate = self;
//    [handle downLoadDataWithURL:kNine_nineProductList key:@"products" model:@"Nine_nine" results:self.waterfallArray];
}

//加载更多数据
- (void)loadMoreData
{
    NSString *pageNumberString=[NSString stringWithFormat:@"&page=%d",pageNumber];
    NSString *urlString = [kNine_nineProductList stringByAppendingString:pageNumberString];
    
    DownLoadData *handle = [DownLoadData shareDataHandle];
    //设置代理
    handle.delegate = self;
    [handle downLoadDataWithURL:urlString key:@"products" model:@"Nine_nine" results:self.waterfallArray];
    
    //加载更多数据执行一次后页码累加1
    pageNumber ++;
}

//刷新数据(handle对象成为代理后实现协议中的方法)
- (void)refresh
{
    [self.collectionView reloadData];
}

#pragma mark ---下拉刷新数据，上拉加载更多数据---

//添加页头下拉刷新控件
- (void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    
    //进入刷新状态就会回调这个Block
    [self.collectionView addHeaderWithCallback:^{
        
        [vc.collectionView reloadData];  //刷新数据
        
        //模拟延迟刷新数据，1秒后才调用，也就是转圈的动作持续1秒！
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [vc.collectionView headerEndRefreshing];  //结束刷新动作
        });
    }];
}

//添加页脚上拉加载控件
- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    
    //进入加载状态就会回调这个Block
    [self.collectionView addFooterWithCallback:^{
        
        [self loadMoreData];  //加载更多数据
        
        //模拟延迟加载数据，2秒后才调用，也就是转圈的动作持续2秒！
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.collectionView footerEndRefreshing];  //结束刷新动作
        });
    }];
}

#pragma mark --- collectionView的代理方法 ---

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.waterfallArray count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    [collectionView registerClass:[Nine_nineCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    Nine_nineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    Nine_nine *nine_nine = self.waterfallArray[indexPath.row];
    cell.nine_nine = nine_nine;
    
    //显示包邮与否
    if ([nine_nine.free_post isEqualToString:@"1"]) {
        cell.free_post_nameLabel.text = [NSString stringWithFormat:@"[包邮]%@",nine_nine.name];
    }
    
    //显示天猫与否
    if ([nine_nine.shop_type isEqualToString:@"B"]) {
        cell.shop_typeImageView.image = [UIImage imageNamed:@"tmall.png"];
    }
    
    //给“市场价格”添加删除线并设置样式
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:cell.market_priceLabel.text];
    NSUInteger length = [cell.market_priceLabel.text length];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length)];
    [cell.market_priceLabel setAttributedText:attri];
    
    [_hud hide:YES];  //数据加载完成将菊花圈隐藏
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    //做一个导航控制器以实现正常跳转和返回
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:detailVC];
    Nine_nine *nine_nine = self.waterfallArray[indexPath.row];
    detailVC.urlString = nine_nine.url;
    [self presentViewController:nav animated:YES completion:nil];
}

//当系统报内存警告时，需要手动进行处理！
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    // Add code to clean up any of your own resources that are no longer necessary.
    
    // 此处做兼容处理需要加上ios6.0的宏开关，保证是在6.0下使用的,6.0以前屏蔽以下代码，否则会在下面使用self.view时自动加载viewDidUnLoad
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
    }
    //self.nine_nineArray = nil;
}

@end